package com.blog.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.blog.dto.User;

public class LoginFilter implements Filter {	
	
	private Set<String> prefixIignores = new HashSet<String>();
	
	private boolean canIgnore(HttpServletRequest request) { 
		String url = request.getRequestURI(); 
		for (String ignore : prefixIignores) { 
//			System.out.println("url------------->"+url); 
			if (url.startsWith(ignore)) { return true; } 
		} 
		return false; 
	}
	
	public void destroy() {
		prefixIignores = null;
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		if (canIgnore(request)) { //不过滤某些文件
			arg2.doFilter(arg0, arg1);
			return;
		}
//		System.out.println(user);	
		if(user == null) {
//			response.sendRedirect(request.getContextPath()+"/login.jsp");
			request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
			return ;
		}else {
			if(user.getSuperstate()==1) {
				request.getRequestDispatcher("/home/index.jsp").forward(request, response);
				return ;
			}
		}
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String cp = config.getServletContext().getContextPath();  
		String ignoresParam = config.getInitParameter("ignores");  
		String[] ignoreArray = ignoresParam.split(",");  
		for (String s : ignoreArray) { 
			prefixIignores.add(cp + s);  
		} 

	}

}
